from flask import Flask, request, Response
import requests

app = Flask(__name__)

OPENAI_API_BASE = 'https://api.openai.com'

# 代理所有发往 /proxy 的请求
@app.route('/proxy/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def proxy(path):
    # 获取请求的方法和头信息
    method = request.method
    headers = dict(request.headers)

    # 构造转发的URL
    url = f"{OPENAI_API_BASE}/{path}"

    # 根据请求的方法转发请求
    if method == 'GET':
        resp = requests.get(url, headers=headers, params=request.args)
    elif method == 'POST':
        resp = requests.post(url, headers=headers, json=request.json)
    elif method == 'PUT':
        resp = requests.put(url, headers=headers, json=request.json)
    elif method == 'DELETE':
        resp = requests.delete(url, headers=headers, json=request.json)
    else:
        return Response("Method not allowed", status=405)

    # 将OpenAI的响应返回给客户端
    return Response(resp.content, status=resp.status_code, headers=dict(resp.headers))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)